package com.demo.springcloud.service.serviceImpl;

import com.demo.springcloud.mapper.TOrderMapper;
import com.demo.springcloud.pojo.CommonResult;
import com.demo.springcloud.pojo.Order;
import com.demo.springcloud.service.TStorageService;
import com.demo.springcloud.service.TAccountService;
import com.demo.springcloud.service.TOrderService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class TOrderServiceImpl implements TOrderService {

	@Autowired
	private TOrderMapper tOrderMapper;
	@Autowired
	private TAccountService accountService;
	@Autowired
	private TStorageService storageService;

	/**
	 * 查询所有记录
	 *
	 * @return 返回集合，没有返回空List
	 */
	@Override
	public List<Order> listAll() {
		return tOrderMapper.listAll();
	}

	/**
	 * 用于测试本模块的是否搭建成功
	 *
	 * @param order
	 * @return
	 */
	@Override
	public int insertTest(Order order) {
		return tOrderMapper.insert(order);
	}

	/**
	 * 新增，插入所有字段
	 *
	 * @param order 新增的记录
	 * @return 返回影响行数
	 */
	@Override
	@GlobalTransactional(name = "fps-create-order", rollbackFor = Exception.class)
	public int insert(Order order) {
		System.out.println(order.toString());
		log.info("--->>>> 开始新建订单 <<<< ");
		int ordering = tOrderMapper.insert(order);

		log.info("--->>>> 订单微服务开始调用 库存，做扣减 <<<< ");
		CommonResult storageResult = storageService.decrease(order.getProductId(), order.getCount());
		Integer storage = (Integer) storageResult.getData();
		log.info("---<<<< 库存 扣减完成 >>>> ");

		log.info("--->>>> 订单微服务开始调用 账户，做扣减 <<<< ");
		CommonResult accountResult = accountService.decrease(order.getUserId(), order.getMoney());
		Integer account = (Integer) accountResult.getData();
		log.info("---<<<< 账户 扣减完成 >>>> ");

		log.info("--->>>> 修改订单状态 <<<< ");
		int update = tOrderMapper.update(order.getId(), 1);
		log.info("---<<<< 状态 修改完成 >>>> ");

		if (ordering > 0 && storage > 0 && account > 0 && update > 0) {
			log.info("---<<<< 订单生成成功 (*^_^*) >>>> ");
			return 1;
		}
		return 0;
	}

	/**
	 * 修改
	 */
	@Override
	public int update(Long id, Integer status) {
		return tOrderMapper.update(id, status);
	}
}
